package com.itboye.hutouben.activity.login;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.itboye.hutouben.R;
import com.itboye.hutouben.activity.mysetting.SettingActivity;
import com.itboye.hutouben.base.BaseActivity;
import com.itboye.hutouben.bean.PersonDataBean;
import com.itboye.hutouben.logincontroller.LoginController;
import com.itboye.hutouben.logincontroller.LoginedState;
import com.itboye.hutouben.permission.PermissionsActivity;
import com.itboye.hutouben.permission.PermissionsChecker;
import com.itboye.hutouben.presenter.UserPresenter;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.Const;
import com.itboye.hutouben.util.IsUtilUid;
import com.itboye.hutouben.util.MyPermission;
import com.itboye.hutouben.util.SPUtils;
import com.itboye.hutouben.volley.ResultEntity;

import java.util.Observable;
import java.util.Observer;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity implements Observer {
    ImageView close_icon;// 返回图片
    TextView add_shap_title_tv;// 标题
    EditText login_username, login_pass;
    ToggleButton login_tb;
    TextView login_ok, login_re, login_wangji;
    UserPresenter userPresenter;

    private static final int REQUEST_CODE = 0; // 请求码
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.MODIFY_AUDIO_SETTINGS
    };
    public static String LOGINEXIT = "com.itboye.ihomebank.exit";// 登录界面推出指令
    private PermissionsChecker mPermissionsChecker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.login_activity);
        userPresenter = new UserPresenter(this);
        MyPermission.CheckPermission(this, Manifest.permission.READ_PHONE_STATE);
        mPermissionsChecker = new PermissionsChecker(this);
        // 短信登录发送过来的广播
        IntentFilter filter1 = new IntentFilter(LOGINEXIT);
        registerReceiver(emailBroadcastReceiver, filter1);
    }


    BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            LoginActivity.this.finish();
        }

        ;
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(emailBroadcastReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拒绝时, 关闭页面, 缺少主要权限, 无法运行
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            finish();
        }
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.login_ok:
                String userName = login_username.getText().toString();
                String pwd = login_pass.getText().toString();
                if (userName.equals("")) {
                    ByAlert.alert("请输入用户名");
                    return;
                }
                if (pwd.equals("")) {
                    ByAlert.alert("请输入密码");
                    return;
                }
                showProgressDialog("登录中,请稍后", true);
                userPresenter.login(userName, pwd);
                break;
            case R.id.login_re:
                intent = new Intent(LoginActivity.this, RegisterOneActivity.class);
                startActivity(intent);

                break;
            case R.id.login_wangji:
                intent = new Intent(LoginActivity.this, PasswordOneActivity.class);
                startActivity(intent);
                break;
            case R.id.login_tb:
                if (login_tb.isChecked()) {
                    login_pass
                            .setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    login_pass.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);

                }
                break;
            default:
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getEventType() == UserPresenter.login_success) {
                Log.d("loginActivity", entity.getData() + "");
                PersonDataBean bean = (PersonDataBean) entity.getData();

                if (bean != null) {

                    SPUtils.put(LoginActivity.this, null,
                            Const.ID, bean.getId());
                    SPUtils.put(LoginActivity.this, null,
                            Const.PaySecret, bean.getPaySecret());
                    SPUtils.put(LoginActivity.this, null,
                            Const.RELE, "6");

                    SPUtils.put(LoginActivity.this, null,
                            Const.USERNAME, bean.getUsername());
                    SPUtils.put(LoginActivity.this, null,
                            Const.PASSWORD, bean.getPassword());
                    SPUtils.put(LoginActivity.this, null,
                            Const.MOBILE, bean.getMobile());
                    SPUtils.put(LoginActivity.this, null,
                            Const.IS_LOGINED, true);
                    SPUtils.put(LoginActivity.this, null,
                            Const.HEAD, bean.getHead());
                    SPUtils.put(LoginActivity.this, null,
                            Const.NICK, bean.getNickname());
                    SPUtils.put(LoginActivity.this, null,
                            Const.YQM, bean.getIdcode());
                    SPUtils.put(LoginActivity.this, null,
                            Const.ISAUTH, bean.getRolesInfo().get(0).getIsAuth());
                    SPUtils.put(LoginActivity.this, null,
                            Const.S_ID, bean.getAutoLoginCode());

                    LoginController.setLoginState(new LoginedState());
                    Intent intent1 = new Intent(SettingActivity.EXITCHANGE);// 通知MeFragment更新界面
                    sendBroadcast(intent1);
                    try {

                        LoginActivity.this.finish();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }


            } else if (entity.getEventType() == UserPresenter.login_fail) {
                ByAlert.alert(entity.getData());
            }
        }
    }
}
